package com.zxb.core.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zxb.core.common.User;
import com.zxb.core.util.TokenUtil;
import com.zxb.core.common.Req;
import com.zxb.core.common.exception.E;
import lombok.AllArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Zxb
 */
@Component
@AllArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean preHandle(
            @Nonnull HttpServletRequest request,
            @Nonnull HttpServletResponse response,
            @Nonnull Object handler) {
        String token = Req.getToken();
        if (StrUtil.isBlank(token)) {
            E.NO_TOKEN.happen();
            return false;
        }
        User u = TokenUtil.validateToken(token);
        if (u == null) {
            E.BAD_TOKEN.happen();
            return false;
        }
        String countSql = "select count(*) from auth_user where username = ?";
        int count = jdbcTemplate.queryForObject(countSql, Integer.class, u.getUsername());
        if (count == 0) {
            E.NO_USER.happen();
            return false;
        }
        return true;
    }
}
